
export const promptMixin = {
  data () {
    return {
      promptVisible: false,
      promptDesc: '',
      promptTimer: null
    }
  },
  methods: {
    // 设置 prompt 的显示隐藏
    setPrompt (desc) {
      // 显示
      this.promptVisible = true
      this.promptDesc = desc
      
      clearTimeout(this.promptTimer)
      // 3秒后自动隐藏
      this.promptTimer = setTimeout(() => {
        this.promptVisible = false
      }, 3000)
    }
  }
}

// 三诺蓝牙SDK
export const snBluetoothMixin = {
  data: {
    timer: null,
    deviceName: "SLX120",
    status: "未连接",  // 连接状态
    deviceId: "",
    code: [],
    bloodLipids: {},  // 血脂数据
    bloodSugar: {}  // 血糖数据
  },
  methods: {
    startConnect() {
      console.log('startConnect 方法执行')
      const _this = this
      wx.openBluetoothAdapter({
        success: res => {
          console.log("初始化蓝牙适配器成功"), _this.getBluetoothAdapterState()
        },
        fail: err => {
          
          wx.showToast({
            title: "请打开手机蓝牙",
            icon: "none",
            duration: 2e3
          })
          
          console.log('初始化蓝牙适配器失败信息：', err)


          // 用户蓝牙开关未开启或者手机不支持蓝牙功能的情况
          if (err.errCode === 10001) {
            // 监听手机蓝牙状态的改变
            wx.onBluetoothAdapterStateChange(res => {
              console.log('startConnect 中的 onBluetoothAdapterStateChange 方法执行：', res)
              // 蓝牙打开，则继续
              if (res.available && !res.discovering) {
                _this.getBluetoothAdapterState()
              } else if (!res.available) {
                this.status = '未连接'

                // 提示用户
                wx.showToast({
                  title: "蓝牙已关闭，请返回连接页面重新连接",
                  icon: "none",
                  duration: 2e3
                })

              }
            })
          }
        }
      })
    },
    getBluetoothAdapterState() {
      const _this = this

      this.status = '开始连接'
      
      wx.getBluetoothAdapterState({
        success: res => {
          _this.startBluetoothDevicesDiscovery()
        }
      })
    },
    startBluetoothDevicesDiscovery() {
      const _this = this
      wx.startBluetoothDevicesDiscovery({
        services: [],
        allowDuplicatesKey: !1,
        success: res => {
          console.log("蓝牙搜索", res), _this.onBluetoothDeviceFound()
        },
        fail: err => {
          console.log(err)
        }
      })
    },
    onBluetoothDeviceFound() {
      const _this = this
      wx.onBluetoothDeviceFound(res => {
        console.log("res.devices", res.devices), 

        res.devices.forEach(device => {
 
          (device.name || device.localName) 
          && -1 != device.name.indexOf(_this.deviceName) 
          && 
          (wx.stopBluetoothDevicesDiscovery({
            success(res) {
              console.log("停止搜寻附近的蓝牙外围设备")
            }
          }), 

          _this.deviceId = device.deviceId, 
          
          console.log("deviceId", _this.deviceId), _this.startConnectDevices())
        })

      })
    },
    startConnectDevices() {
      const _this = this
      console.log("this.deviceId", _this.deviceId), 
      
      wx.createBLEConnection({
        deviceId: _this.deviceId,
        success: res => {
          console.log("蓝牙连接成功")

          _this.status = "蓝牙连接成功"

          // 连接成功后关闭 Loading
          wx.hideLoading()  

          wx.showToast({
            title: _this.status,
            icon: "none",
            duration: 2000
          })

          _this.getBLEDeviceServices()
        },
        fail: res => {
          console.log('蓝牙连接失败')

          _this.status = "蓝牙连接失败"
        }
      })
    },
    getBLEDeviceServices() {
      const _this = this

      wx.getBLEDeviceServices({
        deviceId: _this.deviceId,
        success: res => {
          _this.getCharacter(_this.deviceId, res.services[0].uuid)
        },
        fail: res => {}
      })
    },
    getCharacter: function (deviceId, services) {
      var that = this;
      const _this = this
      wx.getBLEDeviceCharacteristics({
        deviceId: deviceId,
        serviceId: services,
        success: res => {
          console.log("step6蓝牙成功res", res);
          for (let i = 0; i < res.characteristics.length; i++) {
            console.log("res.characteristics", res.characteristics, res.characteristics.length);
            let item = res.characteristics[i];
            (item.properties.notify || item.properties.indicate) && (console.log("进来"), wx.notifyBLECharacteristicValueChange({
              deviceId: deviceId,
              serviceId: services,
              characteristicId: item.uuid,
              state: !0
            })), item.properties.write
          }
        },
        fail: function (err) {},
        complete: function () {}
      }), wx.onBLECharacteristicValueChange(characteristic => {

        console.log("characteristic.value", characteristic.value);

        var chs = [];

        const idx = _this.inArray(chs, "uuid", characteristic.characteristicId);

        let resultVal = _this.ab2hex(characteristic.value),
            result = _this.ab2hex(characteristic.value).split(",");

        console.log("resultVal result", resultVal, result), 

        parseInt("51", 16), _this.code = _this.code.concat(result),

        console.log("code", _this.code), 

        _this.code.length - 3 === parseInt(_this.code[2], 16) && _this.getSimpleData(_this.code)
      })
    },
    getSimpleData(result) {
      const _this = this
      var tang = {
          date: "",
          GLU: {
            name: "",
            value: ""
          }
        },
        object = {
          date: "",
          TC: {
            name: "",
            value: ""
          },
          HDL: {
            name: "",
            value: ""
          },
          TG: {
            name: "",
            value: ""
          },
          LDL: {
            name: "",
            value: ""
          },
          NONHDL: {
            name: "",
            value: ""
          },
          TCHDL: {
            name: "",
            value: ""
          },
          LDHDLL: {
            name: "",
            value: ""
          }
        };
      object.date = "20" + parseInt(result[6], 16) + "-" + parseInt(result[7], 16) + "-" + parseInt(result[8], 16) + " " + parseInt(result[9], 16) + ":" + parseInt(result[10], 16) + ":" + parseInt(result[11], 16), tang.date = object.date;
      let num = parseInt(result[12], 16);
      for (let i = 0; i < num; i++) {
        let arr = [];
        arr = result.slice(13 + 10 * i, 23 + 10 * i), console.log("arr", arr), "00" === arr[1] && (tang.GLU.name = "血糖", tang.GLU.value = parseInt(arr[2] + arr[3], 16)), "03" === arr[1] && (object.TC.name = "血脂TC", object.TC.value = parseInt(arr[2] + arr[3], 16)), "04" === arr[1] && (object.HDL.name = "血脂HDL", object.HDL.value = parseInt(arr[2] + arr[3], 16)), "05" === arr[1] && (object.TG.name = "血脂TG", object.TG.value = parseInt(arr[2] + arr[3], 16)), "06" === arr[1] && (object.LDL.name = "血脂LDL", object.LDL.value = parseInt(arr[2] + arr[3], 16)), "07" === arr[1] && (object.NONHDL.name = "血脂 NONHDL", object.NONHDL.value = parseInt(arr[2] + arr[3], 16)), "08" === arr[1] && (object.TCHDL.name = "血脂 TC / HDL", object.TCHDL.value = parseInt(arr[2] + arr[3], 16)), "09" === arr[1] && (object.LDHDLL.name = "血脂 LDL/HDLL", object.LDHDLL.value = parseInt(arr[2] + arr[3], 16))
      }

      num > 3 ? _this.bloodLipids = object : _this.bloodSugar = tang, 
      console.log("object", object), 

      _this.code = [], 

      console.log("code", _this.code)

    },
    getBluetoothStatus() {
      const _this = this
      wx.showToast({
        title: _this.status,
        icon: "none",
        duration: 2e3
      })
    },
    closeBLEConnection() {
      const _this = this
      let deviceId = this.deviceId;
      wx.closeBLEConnection({
        deviceId: deviceId,
        success: res => {
          console.log(res), wx.showToast({
            title: "断开低功耗蓝牙成功",
            icon: "none",
            duration: 2e3
          }), 

          _this.status = "蓝牙已断开连接"
          _this.bloodLipids = {}
          _this.bloodSugar = {}
        },
        fail: e => {
          wx.showToast({
            title: "断开低功耗蓝牙失败",
            icon: "none",
            duration: 2e3
          })
        }
      })
    },
    closeBluetoothAdapter() {
      const _this = this
      wx.closeBluetoothAdapter({
        success: res => {

          _this.status = "蓝牙模块已关闭"
          _this.bloodLipids = {}
          _this.bloodSugar = {}

          // wx.showToast({
          //   title: "关闭蓝牙模块成功",
          //   icon: "none",
          //   duration: 2e3
          // })
        },
        fail: e => {
          wx.showToast({
            title: "关闭蓝牙模块失败",
            icon: "none",
            duration: 2e3
          })
        }
      })
    },
    ab2hex: function (buffer) {
      var hexArr;
      return Array.prototype.map.call(new Uint8Array(buffer), (function (bit) {
        return ("00" + bit.toString(16)).slice(-2)
      })).join(",")
    },
    inArray: function (arr, key, val) {
      for (let i = 0; i < arr.length; i++)
        if (arr[i][key] === val) return i;
      return -1
    }
  }
}
